﻿using MediatR;
using SmartTracking.API.Read.Application.Commands.SheepFarm_command;
using SmartTracking.Domain.Sheep;
using SmartTracking.Domain.UserInfo;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace SmartTracking.API.Read.Application.CommandHandlers.SheepFarm_handler
{
    public class GetSheepFarmCommandHandler:IRequestHandler<GetSheepFarmCommand,ApiResult<ApiPaging<SheepFarm>>>
    {
        private readonly IBaseRepository<SheepFarm> sheepFarmRep;

        public GetSheepFarmCommandHandler(
            IBaseRepository<SheepFarm> sheepFarmRep)
        {
            this.sheepFarmRep = sheepFarmRep;
        }

        public Task<ApiResult<ApiPaging<SheepFarm>>> Handle(GetSheepFarmCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<SheepFarm>> result = new ApiResult<ApiPaging<SheepFarm>>();
            result.Code = ApiEnum.查询成功;
            result.Message = ApiEnum.查询成功.ToString();

            var list = sheepFarmRep.GetAll().Where(x => x.IsDeleted == false);
            if(!string.IsNullOrEmpty(request.FarmName))
            {
                list = list.Where(x => x.FarmName.Equals(request.FarmName));
            }
            if(!string.IsNullOrEmpty(request.PersonInCharge))
            {
                list = list.Where(x => x.PersonInCharge.Equals(request.PersonInCharge));
            }

            int ListCount = list.Count();
            int PageCount = (int)Math.Ceiling(ListCount * 1.0 / request.PageSize);
            list = list.OrderByDescending(x => x.FarmId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            ApiPaging<SheepFarm> paging = new ApiPaging<SheepFarm>();
            paging.totalCount = ListCount;
            paging.totalPage = PageCount;
            paging.data = list.ToList();

            result.data = paging;
            return Task.FromResult(result);
        }
    }
}
